/*开新场景*/
var cj_editor = {};
// If we are using iOS or desktop
cj_editor.isUsingiOS = false;

cj_editor.configure = '{"yinji_edit_text":[]}';

//If we are using Android
cj_editor.isUsingAndroid = false;

cj_editor.dir_root = "";

cj_editor.img_class = "";

cj_editor.init_run = function(edit_status,usetype){
	if(usetype == "ios"){
		cj_editor.isUsingiOS = true;
	}else if(usetype == "android"){
		cj_editor.isUsingAndroid = true;
	}
	
	if(edit_status == true){
		//callback text config
		cj_editor.getEditorConfig = function(){
			var callback = 'voice,emoj';
			if(cj_editor.isUsingAndroid){
				//alert("通知android键盘条件" + callback);
				getConfig.getConfig(callback);
			}else if(cj_editor.isUsingiOS){
				return callback;
			}else{
				console.log(callback);
			}
		}

		//剪切
		cj_editor.img_tool_change = function(){
			$('.cut').unbind('click');
			$('.cut').bind('click',function(event){
				cj_editor.img_class = "js_cut_img";
				$(this).parent().parent('li').addClass('add_newpic_select_cur');
				var src = $(".add_newpic_select_cur").find('.user_pic').attr("src");
				var CardScalewidth = 0;
				var CardScaleheight = 0;
				if(cj_editor.isUsingAndroid){
					cropPic.cropPic(src,CardScalewidth,CardScaleheight);
				}else if(cj_editor.isUsingiOS){
					cropPic(src,CardScalewidth,CardScaleheight);
				}else{
					console.log(src);
				}
			});
		}

		cj_editor.filteremoji = function(str){
			var ranges = [
				'\ud83c[\udf00-\udfff]',
				'\ud83d[\udc00-\ude4f]',
				'\ud83d[\ude80-\udeff]'
			];
			var emojireg = str;
			emojireg = emojireg.replace(new RegExp(ranges.join('|'), 'g'), '');
			return emojireg;
		}

		cj_editor.getHTML = function(tongbu) {//sync同步  asyn异步
			var callback = arguments[1] ? arguments[1] : '';

			if($.isFunction(cj_editor.userGetHTML)){
				cj_editor.userGetHTML(tongbu);
			}else{
				var result = {"yinji_title":"","yinji_describe":"","yinji_templates_cover":{"type":"image","value":"","attachment":"true"},"yinji_templates_datalist":{"type":"text","value":{},"attachment":"true"},"yinji_templates_date":{"type":"text","value":"","attachment":"false"}};
				if($(".js_title").is("div")){
					result.yinji_title = $(".js_title").text();
				}else{
					result.yinji_title = $(".js_title").val();
				}
				result.yinji_templates_date = $(".js_date").text();
				result.yinji_templates_cover.value = $(".js_cover_pic").attr("PictureStoryImg");
				var loop = 0;
				var img_src = "";
				var img_text = "";
				var location_text = "";
				$("#mess_ul li").each(function(){
					img_text = "";
					if ($(this).hasClass('mess_text')) {
						if($(this).children('.editor_modify').html()){
							img_text = $(this).children('.editor_modify').html();
						}
						result.yinji_templates_datalist.value[loop] = {"text":img_text,"type":"text"};

					}else if ($(this).hasClass('mess_pic')) {
						img_src = '<img src="' + $(this).find('.user_pic').attr("src") + '"\>';
						if($(this).children('.editor_modify').html()){
							img_text = $(this).children('.editor_modify').html();
						}
						/*
						location_text = "";
						if($(this).find('i').text()){
							location_text = $(this).find('.location i').text();
						}
						*/
						result.yinji_templates_datalist.value[loop] = {"text":img_text,"type":"image","src":$(this).find('.user_pic').attr("src"),"catch":img_src};
					}
					if(result.yinji_describe == ""){
						result.yinji_describe = cj_editor.filteremoji($.trim($(this).children('.text_editor').text())).substr(0,32);
					}
					loop++;
				});
				var resultstr = JSON.stringify(result);
				if(callback != ""){
					if(cj_editor.isUsingAndroid){
						getHtmlChangeTemplate.getHtmlChangeTemplate(resultstr,callback);
					}else if(cj_editor.isUsingiOS){
						return resultstr;
					}else{
						console.log(resultstr);
					}
				}else{
					if(cj_editor.isUsingAndroid){
						getHtmlJson.getHtmlJson(resultstr);
					}else if(cj_editor.isUsingiOS){
						return resultstr;
					}else{
						console.log(resultstr);
					}
				}
			}
		}

		//封面图片点击
		$('.js_cover_pic').bind('click',function(event){
			cj_editor.img_class = "js_head_top";

			var CardScalewidth = $(".js_cover_pic").attr("CardScalewidth") * 100;
			var CardScaleheight = $(".js_cover_pic").attr("CardScaleheight") * 100;

			if(cj_editor.isUsingAndroid){
				selectPic.selectPic(CardScalewidth,CardScaleheight);
			}else if(cj_editor.isUsingiOS){
				selectPic(CardScalewidth,CardScaleheight);
			}else{
				console.log("call picture");
			}
		});

		//添加图片
		cj_editor.img_tool_reload = function(src){
			if(cj_editor.img_class == "js_head_top"){
				$(".js_cover_pic").attr("PictureStoryImg",src);
				$('#cover_pic').css({'backgroundImage':'url(' + cj_editor.dir_root + 'images/zhezhao.png),url(' + src + ')'});
			}else if(cj_editor.img_class == "user_image"){
				
				var src_r = src.split(",");
				/*
				if(user_location){
					var user_location_obj = user_location.split(',');
				}
				*/
				$.each(src_r, function(index, content){
					if(content != ""){
						/*
						if(user_location_obj && user_location_obj[index]){
							cj_editor.add_new_pic(content,user_location_obj[index]);
						}else{
							cj_editor.add_new_pic(content);
						}
						*/
						cj_editor.add_new_pic(content);
						$('ul li').removeClass('add_newmess_animation');
					}
				});
				$(".add_newmess").removeClass('add_newmess_select_cur');

			}else if(cj_editor.img_class == "js_cut_img"){
				$(".add_newpic_select_cur").find('.user_pic').attr("src",src);
				$(".add_newpic_select_cur").removeClass('add_newpic_select_cur');
			}
		}

		//清理标记图片
		cj_editor.img_tool_clear_newpic = function(){
				$(".add_newpic_select_cur").removeClass('add_newpic_select_cur');
		}

		//时间点击设置
		$('.js_set_time').bind('click',function(event){
			cj_editor.callUpdateDate();
		});

		//标题
		/*
		$('.js_title').bind('click',function(event){
			var that = $(this);
			$('.text_editor').removeClass('text_editor_cur');
			that.attr('contenteditable', 'true');
			that.focus();
			if($.isFunction(cj_editor.text_clear)){
				cj_editor.text_clear(that);
			}
		});
		*/
	}else{
		//点击通知
		var startX = 0,touchmove = 0;
		$('body').on('touchstart',function(e){
		   startX = e.originalEvent.changedTouches[0].pageX,
		   startY = e.originalEvent.changedTouches[0].pageY;
		});

		$('body').on('touchend',function(e){
		   //获取滑动屏幕时的X,Y
		   endX = e.originalEvent.changedTouches[0].pageX,
		   endY = e.originalEvent.changedTouches[0].pageY;
		   //获取滑动距离
		   distanceX = endX-startX;
		   distanceY = endY-startY;
		   if(Math.abs(distanceX) < 5 && Math.abs(distanceY) < 5){
				if(e.target.nodeName != "IMG"){
					if(cj_editor.isUsingAndroid){
						ClickScreen.clickScreen();
					}else if(cj_editor.isUsingiOS){
						showBrowsteNav();
					}else{
						console.log("click");
					}
				}
		   }
		});
		
		//大图浏览
		cj_editor.autoImg = function(){
			$('.mess_pic').find('.user_pic').click(function() {
					var src = $(this).attr("src");
					var imglist = "";
					$(".mess_pic img").each(function(){
						if($(this).attr("src") != "images/btn_delete.png" && $(this).attr("src") != "images/btn_cut.png"){
							imglist += $(this).attr("src") + ",";
						}
					});
					if(cj_editor.isUsingAndroid){
						LookBigPic.lookBigPic(src,imglist);
					}else if(cj_editor.isUsingiOS){
						showImageSrc(src,imglist);
					}else{
						console.log(imglist);
					}
			});
		}
	}

	cj_editor.title_editor = function(){   //标题编辑事件（编辑状态）
		  var textArea = $('#title');
		  cj_editor.title_key_set(textArea,64);
	}

	cj_editor.title_key_set = function(textArea,maxlength){   //标题字数限制监控（64字）
		  textArea[0].setAttribute("maxlength", maxlength);
		  var text = document.getElementById('title');
		  cj_editor.autoTextarea(text);
	}

	cj_editor.autoTextarea = function(elem, extra, maxHeight) {
			extra = extra || 0;
			var isFirefox = !!document.getBoxObjectFor || 'mozInnerScreenX' in window,
			isOpera = !!window.opera && !!window.opera.toString().indexOf('Opera'),
					addEvent = function (type, callback) {
							elem.addEventListener ?
									elem.addEventListener(type, callback, false) :
									elem.attachEvent('on' + type, callback);
					},
					getStyle = elem.currentStyle ? function (name) {
							var val = elem.currentStyle[name];
	 
							if (name === 'height' && val.search(/px/i) !== 1) {
									var rect = elem.getBoundingClientRect();
									return rect.bottom - rect.top -
											parseFloat(getStyle('paddingTop')) -
											parseFloat(getStyle('paddingBottom')) + 'px';        
							};
	 
							return val;
					} : function (name) {
									return getComputedStyle(elem, null)[name];
					},
					minHeight = parseFloat(getStyle('height'));
	 
			elem.style.resize = 'none';
	 
			var change = function () {
					var scrollTop, height,
							padding = 0,
							style = elem.style;
	 
					if (elem._length === elem.value.length) return;
					elem._length = elem.value.length;
	 
					if (!isFirefox && !isOpera) {
							padding = parseInt(getStyle('paddingTop')) + parseInt(getStyle('paddingBottom'));
					};
					scrollTop = document.body.scrollTop || document.documentElement.scrollTop;
	 
					elem.style.height = minHeight + 'px';
					if (elem.scrollHeight > minHeight) {
							if (maxHeight && elem.scrollHeight > maxHeight) {
									height = maxHeight - padding;
									style.overflowY = 'auto';
							} else {
									height = elem.scrollHeight - padding;
									style.overflowY = 'hidden';
							};
							style.height = height + extra + 'px';
							scrollTop += parseInt(style.height) - elem.currHeight;
							document.body.scrollTop = scrollTop;
							document.documentElement.scrollTop = scrollTop;
							elem.currHeight = parseInt(style.height);
					};
			};
	 
			addEvent('propertychange', change);
			addEvent('input', change);
			addEvent('focus', change);
			change();
	}

	cj_editor.insertVideoImage = function(url, alt, text){
		zss_editor.insertHTML(text);
		return true;
	}

	cj_editor.insertText = function(text){
		zss_editor.insertHTML(text);
		return true;
	}

	//时间设置
	cj_editor.setDate = function(time){
		if($.isFunction(cj_editor.customDate)){
			cj_editor.customDate();
		}else{
			var date = new Date(time * 1);
			var year = date.getFullYear();
			var month = date.getMonth() + 1 < 10 ? "0" + (date.getMonth() + 1) : date.getMonth() + 1;
			var day = date.getDate() < 10 ? "0" + date.getDate() : date.getDate();
			$(".js_date").text(year + "." + month + "." + day);
		}
	}

	//呼唤时间
	cj_editor.callUpdateDate = function(){
		if(cj_editor.isUsingAndroid){
			EditTime.editTime("sync");
		}else if(cj_editor.isUsingiOS){
			editTime("sync");
		}else{
			console.log("calldate");
		}
	}
	
	cj_editor.setHTML = function(data) {
		if($.isFunction(cj_editor.userSetHTML)){
			cj_editor.userSetHTML(tongbu);
		}else{
			if($.isFunction(cj_editor.setDefaultStart)){
				cj_editor.setDefaultStart();
			}
			var data_obj = data;
			$.each(data_obj, function(index, content){ 
				if(index == "yinji_templates_datalist"){
					var loop = 0;
					redata = content.value;
					$.each(redata, function(item_key, item_value){ 
						if(item_value.type == "text"){
							cj_editor.load_user_mess_text(item_value.text);
						}else if(item_value.type == "image"){
							cj_editor.load_user_mess_pic(item_value.text,item_value.src,item_value.location);
						}
						$('ul li').removeClass('add_newmess_animation');
					});
				}else if(index == "yinji_title"){
					if($(".js_title").is("div")){
						$(".js_title").text(content);
					}else{
						$(".js_title").val(content);
					}
				}else if(index == "yinji_templates_date"){
					$(".js_date").text(content);
				}else if(index == "yinji_templates_cover"){
					$(".js_cover_pic").attr("PictureStoryImg",content.value);
					$('#cover_pic').css({'backgroundImage':'url(' + cj_editor.dir_root + 'images/zhezhao.png),url(' + content.value + ')'});
				}

			});
			if($.isFunction(cj_editor.SeDefaultEnd)){
				cj_editor.SeDefaultEnd();
			}
		}
	}
	
	cj_editor.countText = function(){
		var value = $.trim($('.js_title').text()).replace(/[s+|\s]/g,"").length;
		$("#mess_ul li").each(function(){
			if ($(this).hasClass('mess_text')) {
				value = value + $.trim($(this).children('.text_editor').text()).replace(/[s+|\s]/g,"").length;
			}else if ($(this).hasClass('mess_pic')) {
				value = value + $.trim($(this).children('.text_editor').text()).replace(/[s+|\s]/g,"").length;
			}
		});
		return value;
	}

	cj_editor.countImage = function(){
		var value = 0;
		$("#mess_ul li").each(function(){
			if ($(this).hasClass('mess_pic')) {
				value = value + 1;
			}
		})
		return value;
	}

	cj_editor.countAudio = function(){
		var value = 0;
		$("#mess_ul li").each(function(){
			if($(this).children('.text_editor').hasClass("yinji_templates_voice_play_audio")){
				value = value + 1;
			}
		});
		return value;
	}

	cj_editor.countAll = function(){
		var countall = "";
		countall = cj_editor.countText()+","+cj_editor.countImage()+","+cj_editor.countAudio();
		if(cj_editor.isUsingAndroid){
			window.GetHtmlPageData.countAllData(countall);
		}else if(cj_editor.isUsingiOS){
			return countall;
		}else{
			console.log(countall);
		}
	}
}

cj_editor.adaptive_size = function(designWidth,rem2px){
	var d = window.document.createElement('div');   //创建模型
	d.style.width = '1rem';
	d.style.display = 'none';
	var head = window.document.getElementsByTagName('head')[0];
	head.appendChild(d);
	var defaultFontSize = parseFloat(window.getComputedStyle(d,null).getPropertyValue('width'));
	d.remove();
	var boxWidth = $('.yinji_templates_PictureStory_box').outerWidth();
	document.documentElement.style.fontSize = boxWidth / designWidth * rem2px / defaultFontSize * 100 + '%';
	var st = document.createElement('style');
	var portrait = "@media screen and (min-width:" + boxWidth + "px) {html{font-size:" + ((boxWidth / (designWidth / rem2px) / defaultFontSize) * 100) + "%}}";
	var landscape = "@media screen and (min-width:" + window.innerHeight + "px) {html{font-size:" + ((window.innerHeight / (designWidth / rem2px) / defaultFontSize) * 100) + "%}}";
	st.innerHTML = portrait + landscape;
	head.appendChild(st);
	return defaultFontSize;
}